<?php 
require_once (dirname(__FILE__)."/services.php");

/**
 * com_yizin_site_admin_user_user_page_2
 *
 * 后台显示用户列表
 *
 * @param object $matches
 * 	 $matches[2]：获得用户信息的页数以便分页，或返回第一页
 *
 * @mvc
 * 	 渲染:$mvc->render(dirname(__FILE__)."/views/_admin_user_user_.php");
 */
function com_yizin_site_admin_user_user_page_2($matches) {

    global $mvc;
    $page = $matches[2] ? $matches[2] : 1;
    $size = 50;
    $count = user_getCount();
    $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."admin/user/user/page/${page}/");
    $users = user_getAll(($page - 1) * $size, $size, "serial");
    $GLOBALS['users'] = $users;
    $GLOBALS['pageNav'] = $pageNav;
    $GLOBALS['message'] = $mvc->getMessage('message');
    $mvc->render(dirname(__FILE__)."/views/_admin_user_user_.php");
}

/**
 * com_yizin_site_admin_user_user_1_2_page_4
 *
 * 后台搜索用户信息列表
 *
 * @param object $matches
 * 	 $matches[1]：获得所要搜索的列名称
 * 	 $matches[2]：获得所要搜索的内容
 * 	 $matches[4]：获得查询结果条目的页数以便分页,或返回第一页
 *
 * @mvc
 * 	 渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_user_.php");
 */
 
function com_yizin_site_admin_user_user_1_2_page_4($matches) {

    global $mvc;
    $facet = $matches[1];
    $keyword = urldecode($matches[2]);
    $page = $matches[4] ? $matches[4] : 1;
    $size = 50;
    $count = user_getCountSearchByFacet($facet, $keyword);
    $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."admin/user/user/$facet/$keyword/page/${page}/");
    $users = user_getAllSearchByFacet($facet, $keyword, ($page - 1) * $size, $size, "serial");
    $GLOBALS['users'] = $users;
    $GLOBALS['pageNav'] = $pageNav;
    $GLOBALS['message'] = $mvc->getMessage('message');
    $GLOBALS['facet'] = $facet;
    $GLOBALS['keyword'] = $keyword;
    $mvc->render(dirname(__FILE__)."/views/_admin_user_user_.php");
}

/**
 * com_yizin_site_admin_user_user_new
 *
 * 进入后台创建用户页面
 *
 * @mvc
 * 	  渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_user_new_.php");
 */
 
function com_yizin_site_admin_user_user_new($matches) {

    global $mvc;
    $mvc->render(dirname(__FILE__)."/views/_admin_user_user_new_.php");
}

/**
 * com_yizin_site_admin_user_user_create
 *
 * 后台创建用户提交
 *
 * @mvc
 * 	 if（表单有错误）渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_user_new_.php");
 * 	 else：跳转：$mvc->redirect(REQUEST_BASE."admin/user/user/");
 */
 
function com_yizin_site_admin_user_user_create($matches) {

    global $mvc;
    
    $id = trim($_POST['id']);
    $email = trim($_POST['email']);
    $nickname = trim($_POST['nickname']);
    $description = trim($_POST['description']);
    $password = trim($_POST['password']);
    $password1 = trim($_POST['password1']);
    
    $city = trim($_POST['city']);
    $company = trim($_POST['company']);
    
    $error = array();
    if ($id == "") {
        $error['id'] = "用户名不能为空";
    } elseif (!Utils::isIdentifier($id)) {
        $error['id'] = "用户名必须由字母或数字组成，数字开头";
    } elseif (strlen($id) < 4 || strlen($id) > 20) {
        $error['id'] = "用户名长度必须在4-20之间";
    } elseif ($email == "") {
        $error['email'] = "邮箱不能为空";
    } elseif (!Utils::isEmail($email)) {
        $error['email'] = "邮箱不符合要求";
    } elseif ($nickname != "" && (strlen($nickname) < 4 || strlen($nickname) > 20)) {
        $error['nickname'] = "昵称长度必须在4-20之间";
    } elseif ($password == "") {
        $error['password'] = "密码不能为空";
    } elseif (strlen($password) < 6 || strlen($password) > 30) {
        $error['password'] = "密码长度必须在6-30之间";
    } elseif ($password1 != $password) {
        $error['password1'] = "必须和上面的密码相同";
    }
    
    if (count($error) == 0) {
        $user = user_getByField('id', $id);
        if ($user) {
            $error['id'] = "用户名已存在";
        }
    }
    
    if (count($error) == 0) {
        $user = user_getByField('email', $email);
        if ($user) {
            $error['email'] = "邮箱已存在";
        }
    }
    
    if (count($error) != 0) {
        $GLOBALS['error'] = $error;
        $GLOBALS['id'] = $id;
        $GLOBALS['email'] = $email;
        $GLOBALS['nickname'] = $nickname;
        $GLOBALS['description'] = $description;
        
        $GLOBALS['password'] = $password;
        $GLOBALS['password1'] = $password1;
        
        $GLOBALS['city'] = $city;
        $GLOBALS['company'] = $company;
        
        $mvc->render(dirname(__FILE__)."/views/_admin_user_user_new_.php");
        return;
    }
    
    $nickname = $nickname ? $nickname : $id;
    
    $serial = user_create(array('id'=>$id, 'email'=>$email, 'nickname'=>$nickname, 'password'=>$password, 'description'=>$description));
    
    $user_profile = user_profile_create($serial, array('city'=>$city, 'company'=>$company));
    
    if ($serial && $user_profile) {
        $mvc->setMessage("message", "添加用户成功");
        $mvc->redirect(REQUEST_BASE."admin/user/user/");
    }
    
}

/**
 * com_yizin_site_admin_user_user_delete
 *
 * 后台删除用户信息
 *
 * @mvc
 * 	 跳转：$mvc->redirect(REQUEST_BASE."admin/user/user/");
 */
 
function com_yizin_site_admin_user_user_delete($matches) {

    global $mvc;
    
    $serials = $_POST['serials'];
    $serialsArray = split(",|，", $serials);
    $serials = array();
    foreach ($serialsArray as $serial) {
        $serials[] = trim($serial);
    }
    user_deleteByField('serial', $serials);
    $mvc->setMessage("message", "删除用户成功");
    $mvc->redirect(REQUEST_BASE."admin/user/user/");
}

/**
 * com_yizin_site_admin_user_user_1
 *
 * 后台编辑用户信息
 *
 * @param object $matches
 * 	 $matches[1]：获得对应用户的$serial
 *
 * @mvc
 * 	 get：渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_user_edit_.php");
 * 	 post：if（表单有错误）$mvc->render(dirname(__FILE__)."/views/_admin_user_user_edit_.php");
 * 	       else：跳转：$mvc->redirect(REQUEST_BASE."admin/user/user/")；
 */
 
function com_yizin_site_admin_user_user_1($matches) {

    global $mvc;
    
    $serial = $matches[1];
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $user = user_getXByField('serial', $serial);
        if ($user) {
            $GLOBALS['serial'] = $user['serial'];
            $GLOBALS['id'] = $user['id'];
            $GLOBALS['email'] = $user['email'];
            $GLOBALS['nickname'] = $user['nickname'];
            $GLOBALS['description'] = $user['description'];
        }
        $mvc->render(dirname(__FILE__)."/views/_admin_user_user_edit_.php");
    } elseif ($method == "POST") {
        $id = trim($_POST['id']);
        $email = trim($_POST['email']);
        $nickname = trim($_POST['nickname']);
        $description = trim($_POST['description']);
        $password = trim($_POST['password']);
        $password1 = trim($_POST['password1']);
        
        $error = array();
        if ($id == "") {
            $error['id'] = "用户名不能为空";
        } elseif (!Utils::isIdentifier($id)) {
            $error['id'] = "用户名必须由字母或数字组成，数字开头";
        } elseif (strlen($id) < 4 || strlen($id) > 20) {
            $error['id'] = "用户名长度必须在4-20之间";
        } elseif ($email == "") {
            $error['email'] = "邮箱不能为空";
        } elseif (!Utils::isEmail($email)) {
            $error['email'] = "邮箱不符合要求";
        } elseif ($nickname != "" && (strlen($nickname) < 4 || strlen($nickname) > 20)) {
            $error['nickname'] = "昵称长度必须在4-20之间";
        } elseif ($password != "" && (strlen($password) < 6 || strlen($password) > 30)) {
            $error['password'] = "密码长度必须在6-30之间";
        } elseif ($password != "" && ($password1 != $password)) {
            $error['password1'] = "必须和上面的密码相同";
        }
        
        if (count($error) == 0) {
            $user = user_getByField('id', $id);
            if ($user && $user['serial'] != $serial) {
                $error['id'] = "用户名已存在";
            }
        }
        
        if (count($error) == 0) {
            $user = user_getByField('email', $email);
            if ($user && $user['serial'] != $serial) {
                $error['email'] = "邮箱已存在";
            }
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['serial'] = $serial;
            $GLOBALS['id'] = $id;
            $GLOBALS['email'] = $email;
            $GLOBALS['nickname'] = $nickname;
            $GLOBALS['description'] = $description;
            
            $mvc->render(dirname(__FILE__)."/views/_admin_user_user_edit_.php");
            return;
        }
        
        $nickname = $nickname ? $nickname : $id;
        
        $user = array('serial'=>$serial,
                 'id'=>$id,
                 'email'=>$email,
                 'nickname'=>$nickname,
                 'description'=>$description);
        
        if ($password) {
            $user['password'] = $password;
        }
        user_update($user);
        
        $mvc->setMessage("message", "修改用户成功");
        $mvc->redirect(REQUEST_BASE."admin/user/user/");
        
    }
}

/**
 * com_yizin_site_admin_user_profile_1
 *
 * 后台查询用户个人资料
 *
 * @param object $matches
 * 	 $matches[1]：获得对应用户的$serial
 *
 * @mvc
 * 	 渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_profile_.php");
 */
 
function com_yizin_site_admin_user_profile_1($matches) {

    global $mvc;
    
    $serial = $matches[1];
    
    $user = user_getXByField('serial', $serial);
    if ($user) {
        $GLOBALS['serial'] = $user['serial'];
        $GLOBALS['id'] = $user['id'];
        $GLOBALS['email'] = $user['email'];
        $GLOBALS['nickname'] = $user['nickname'];
        $GLOBALS['description'] = $user['description'];
    }
    
    $profiles = user_getProfiles($serial);
    if ($profiles) {
        $GLOBALS['profiles'] = $profiles;
    }
    
    $mvc->render(dirname(__FILE__)."/views/_admin_user_profile_.php");
}

/**
 * com_yizin_site_admin_user_role_page_2
 *
 * 查看角色列表
 *
 * @param object $matches
 * 	 $matches[2]：获得角色信息所用页数以便分页，或返回第一页
 *
 * @mvc
 * 	 渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_.php");
 */
 
function com_yizin_site_admin_user_role_page_2($matches) {

    global $mvc;
    $page = $matches[2] ? $matches[2] : 1;
    $size = 50;
    $count = role_getCount();
    $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."admin/user/role/page/${page}/");
    $roles = role_getAll(($page - 1) * $size, $size, "serial");
    $GLOBALS['roles'] = $roles;
    $GLOBALS['pageNav'] = $pageNav;
    $GLOBALS['message'] = $mvc->getMessage('message');
    $mvc->render(dirname(__FILE__)."/views/_admin_user_role_.php");
}

/**
 * com_yizin_site_admin_user_role_new
 *
 * 进入创建角色页面
 *
 * @mvc
 * 	 渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_new_.php");
 }
 */
 
function com_yizin_site_admin_user_role_new($matches) {

    global $mvc;
    $mvc->render(dirname(__FILE__)."/views/_admin_user_role_new_.php");
}

/**
 * com_yizin_site_admin_user_role_create
 *
 * 创建角色
 *
 * @mvc
 * 	 if（表单有错误）渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_new_.php");
 * 	 else：跳转：$mvc->redirect(REQUEST_BASE."admin/user/role/");
 */
 
function com_yizin_site_admin_user_role_create($matches) {

    global $mvc;
    
    $id = trim($_POST['id']);
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    
    $error = array();
    if ($id == "") {
        $error['id'] = "ID不能为空";
    } elseif (!Utils::isIdentifier($id)) {
        $error['id'] = "ID必须由字母或数字组成，数字开头";
    } elseif (strlen($id) < 1 || strlen($id) > 20) {
        $error['id'] = "用户名长度必须在1-20之间";
    } elseif ($name == "") {
        $error['name'] = "名称不能为空";
    } elseif (strlen($name) < 1 || strlen($name) > 20) {
        $error['name'] = "名称长度必须在1-20之间";
    }
    
    if (count($error) == 0) {
        $role = role_getByField('id', $id);
        if ($role) {
            $error['id'] = "ID已存在";
        }
    }
    
    if (count($error) == 0) {
        $role = role_getByField('name', $name);
        if ($role) {
            $error['name'] = "名称已存在";
        }
    }
    
    if (count($error) != 0) {
        $GLOBALS['error'] = $error;
        $GLOBALS['id'] = $id;
        $GLOBALS['name'] = $name;
        $GLOBALS['description'] = $description;
        
        $mvc->render(dirname(__FILE__)."/views/_admin_user_role_new_.php");
        return;
    }
    
    $serial = role_create(array('id'=>$id, 'name'=>$name, 'description'=>$description));
    
    if ($serial) {
        $mvc->setMessage("message", "添加角色成功");
        $mvc->redirect(REQUEST_BASE."admin/user/role/");
    }
    
}

/**
 * com_yizin_site_admin_user_role_delete
 *
 * 删除角色
 *
 * @mvc
 * 	  跳转：$mvc->redirect(REQUEST_BASE."admin/user/role/");
 */
 
function com_yizin_site_admin_user_role_delete($matches) {

    global $mvc;
    
    $serials = $_POST['serials'];
    $serialsArray = split(",|，", $serials);
    $serials = array();
    foreach ($serialsArray as $serial) {
        $serial = trim($serial);
        $role = role_getByField('serial', $serial);
        if (!in_array($role['id'], role_getPreserved())) {
            $serials[] = $serial;
        }
    }
    role_deleteByField('serial', $serials);
    $mvc->setMessage("message", "删除角色成功");
    $mvc->redirect(REQUEST_BASE."admin/user/role/");
}

/**
 * com_yizin_site_admin_user_role_1
 *
 * 编辑角色信息
 *
 * @param object $matches
 * 	 $matches[1]：获得对应角色的$serial
 *
 * @mvc
 * 	 get：渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_edit_.php");
 * 	 post：if（表单有错）$mvc->render(dirname(__FILE__)."/views/_admin_user_role_edit_.php");
 * 	       else：跳转：$mvc->redirect(REQUEST_BASE."admin/user/role/");
 */
 
function com_yizin_site_admin_user_role_1($matches) {

    global $mvc;
    
    $serial = $matches[1];
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
    
        $role = role_getByField('serial', $serial);
        if ($role) {
            $GLOBALS['serial'] = $role['serial'];
            $GLOBALS['id'] = $role['id'];
            $GLOBALS['name'] = $role['name'];
            $GLOBALS['description'] = $role['description'];
            $GLOBALS['preserved'] = in_array($role['id'], role_getPreserved());
        }
        
        $mvc->render(dirname(__FILE__)."/views/_admin_user_role_edit_.php");
    } elseif ($method == "POST") {
        $id = trim($_POST['id']);
        $name = trim($_POST['name']);
        $description = trim($_POST['description']);
        
        $error = array();
        if ($id == "") {
            $error['id'] = "ID不能为空";
        } elseif (!Utils::isIdentifier($id)) {
            $error['id'] = "ID必须由字母或数字组成，数字开头";
        } elseif (strlen($id) < 1 || strlen($id) > 20) {
            $error['id'] = "ID长度必须在1-20之间";
        } elseif ($name == "") {
            $error['name'] = "名称不能为空";
        } elseif ($name != "" && (strlen($name) < 1 || strlen($name) > 20)) {
            $error['name'] = "名称长度必须在1-20之间";
        }
        
        if (count($error) == 0) {
            $role = role_getByField('id', $id);
            if ($role && $role['serial'] != $serial) {
                $error['id'] = "ID已存在";
            }
        }
        
        //not allow modify the id of a preserved role
        if (count($error) == 0) {
            $role = role_getByField('serial', $serial);
            if (in_array($role['id'], role_getPreserved()) && $role['id'] != $id) {
                $error['id'] = "不能修改预设角色的ID";
            }
        }
        
        if (count($error) == 0) {
            $role = role_getByField('name', $name);
            if ($role && $role['serial'] != $serial) {
                $error['name'] = "名称已存在";
            }
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['serial'] = $serial;
            $GLOBALS['id'] = $id;
            $GLOBALS['name'] = $name;
            $GLOBALS['description'] = $description;
            
            $mvc->render(dirname(__FILE__)."/views/_admin_user_role_edit_.php");
            return;
        }
        
        $role = array('serial'=>$serial, 'id'=>$id, 'name'=>$name, 'description'=>$description);
        
        role_update($role);
        
        $mvc->setMessage("message", "修改角色成功");
        $mvc->redirect(REQUEST_BASE."admin/user/role/");
        
    }
}

/**
 * com_yizin_site_admin_user_role_1_privilege
 *
 * 编辑角色权限
 *
 * @param object $matches
 * 	 $matches[1]：获得对应角色的$serial
 *
 * @mvc
 * 	 get：渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_privilege_edit_.php");
 * 	 post：跳转：$mvc->redirect(REQUEST_BASE."admin/user/role/");
 *
 * @扩展点：
 * 	 $featureManager->apply("com.yizin.platform.privilege", $privilege);
 * 	 $featureManager->apply("com.yizin.platform.privilege", $privilege);
 */
 
function com_yizin_site_admin_user_role_1_privilege($matches) {

    global $mvc;
    
    $serial = $matches[1];
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $role = role_getByField('serial', $serial);
        if ($role) {
            global $featureManager;
            $featureManager->apply("com.yizin.platform.privilege", $privilege);
            
            $array1 = array();
            foreach ($privilege['items'] as $key1=>$item1) {
                $temp = array();
                
                foreach ($item1['items'] as $key2=>$item2) {
                    $temp[$key2] = array("text"=>$item2['text'], "items"=>array());
                }
                $array1[$key1] = array("text"=>$item1['text'], "items"=>$temp);
                
            }
            $privilegeArray = array("items"=>$array1);
            
            $privilegeJson = json_encode($privilegeArray);
            $privilege = privilege_get($serial, $privilege);
            
            $GLOBALS['serial'] = $serial;
            $GLOBALS['privilege'] = $privilege;
            $GLOBALS['privilegeJson'] = $privilegeJson;
            $mvc->render(dirname(__FILE__)."/views/_admin_user_role_privilege_edit_.php");
        }
    } elseif ($method == "POST") {
        global $featureManager;
        $featureManager->apply("com.yizin.platform.privilege", $privilege);
        foreach ($privilege['items'] as $key1=>$item1) {
            $on = true;
            foreach ($item1['items'] as $key2=>$item2) {
                if ($_POST["privilege_".$key1."_".$key2] == "on") {
                    $privilege['items'][$key1]['items'][$key2]['allow'] = true;
                } else {
                    $on = false;
                    $privilege['items'][$key1]['items'][$key2]['allow'] = false;
                }
            }
            if ($on) {
                $privilege['items'][$key1]['allow'] = true;
            } else {
                $privilege['items'][$key1]['allow'] = false;
            }
        }
        
        $default = ($_POST['privilege_default'] == "on");
        $privilege['default'] = $default;
        privilege_update($serial, $privilege);
        
        $mvc->setMessage("message", "编辑权限成功");
        $mvc->redirect(REQUEST_BASE."admin/user/role/");
    }
}

/**
 *
 * @param object $matches
 *
 * @mvc
 *	 get：渲染：$mvc->render(dirname(__FILE__)."/views/_admin_user_role_grant_.php");
 *	 post：if（表单有错）$mvc->render(dirname(__FILE__)."/views/_admin_user_role_grant_.php");
 else if($from == 'user')跳转：$mvc->redirect(REQUEST_BASE."admin/user/user/");
 else：跳转：$mvc->redirect(REQUEST_BASE."admin/user/role/");
 */
 
function com_yizin_site_admin_user_role_grant($matches) {

    global $mvc;
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $userSerials = $_GET['userSerials'];
        $roleSerial = $_GET['roleSerial'];
        $from = $_GET['from'];
        
        $userSerialsArray = split(",|，", $userSerials);
        $userSerials = array();
        foreach ($userSerialsArray as $userSerial) {
            $userSerials[] = trim($userSerial);
        }
        $users = user_getByField("serial", $userSerials);
        $userIds = array();
        foreach ($users as $user) {
            $userIds[] = $user['id'];
        }
        $userIds = join($userIds, ",");
        
        $role = role_getByField("serial", $roleSerial);
        $roleId = $role['id'];
        
        $GLOBALS['userIds'] = trim($userIds);
        $GLOBALS['roleId'] = trim($roleId);
        $GLOBALS['from'] = trim($from);
        $mvc->render(dirname(__FILE__)."/views/_admin_user_role_grant_.php");
    } elseif ($method == "POST") {
    
        $userIds = trim($_POST['userIds']);
        $roleId = trim($_POST['roleId']);
        $from = trim($_POST['from']);
        
        $error = array();
        if ($userIds == "") {
            $error['userIds'] = "用户名不能为空";
        } elseif ($roleId == "") {
            $error['roleId'] = "名称不能为空";
        }
        
        $users = array();
        if (count($error) == 0) {
            $userIdArray = split(",|，", $userIds);
            foreach ($userIdArray as $userId) {
                $userId = trim($userId);
                $user = user_getByField('id', $userId);
                $users[] = $user;
                if (!$user) {
                    $error['userIds'] = "用户名${userId}不存在";
                    break;
                }
            }
        }
        
        if (count($error) == 0) {
            $role = role_getByField('id', $roleId);
            if (!$role) {
                $error['roleId'] = "角色不存在";
            }
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['userIds'] = $userIds;
            $GLOBALS['roleId'] = $roleId;
            $GLOBALS['from'] = $from;
            
            $mvc->render(dirname(__FILE__)."/views/_admin_user_role_grant_.php");
            return;
        }
        
        $userSerials = array();
        foreach ($users as $user) {
            $userSerials[] = $user['serial'];
        }
        role_grant($userSerials, $role['serial']);
        
        if ($from == 'user') {
            $mvc->setMessage("message", "设置角色成功");
            $mvc->redirect(REQUEST_BASE."admin/user/user/");
        } else {
            $mvc->setMessage("message", "设置用户成功");
            $mvc->redirect(REQUEST_BASE."admin/user/role/");
        }
    }
}

/**
 * com_yizin_site_register
 *
 * 用户注册
 *
 * @mvc
 * 	 get:渲染：$mvc->render(dirname(__FILE__)."/views/_register_.php");
 * 	 post：if（表单有错误）渲染：$mvc->render(dirname(__FILE__)."/views/_register_.php");
 * 	       else：跳转：$mvc->redirect(REQUEST_BASE);
 */
 
function com_yizin_site_register($matches) {

    global $mvc;
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $mvc->render(dirname(__FILE__)."/views/_register_.php");
    } elseif ($method == "POST") {
        global $mvc;
        
        $id = trim($_POST['id']);
        $email = trim($_POST['email']);
        $password = trim($_POST['password']);
        $password1 = trim($_POST['password1']);
        
        $error = array();
        if ($id == "") {
            $error['id'] = "Username is required.";
        } elseif (!Utils::isIdentifier($id)) {
            $error['id'] = "Username should contain only letters or numbers, and begin with letter.";
        } elseif (strlen($id) < 4 || strlen($id) > 20) {
            $error['id'] = "Username size should between 4 and 20.";
        } elseif ($email == "") {
            $error['email'] = "E-mail is required.";
        } elseif (!Utils::isEmail($email)) {
            $error['email'] = "Invalid E-mail";
        }  elseif ($password == "") {
            $error['password'] = "Password is required.";
        } elseif (strlen($password) < 6 || strlen($password) > 30) {
            $error['password'] = "Password size should between 6 and 30.";
        } elseif ($password1 != $password) {
            $error['password1'] = "The two password is different, please check it again.";
        }
        
        if (count($error) == 0) {
            $user = user_getByField('id', $id);
            if ($user) {
                $error['id'] = "Username exists.";
            }
        }
        
        if (count($error) == 0) {
            $user = user_getByField('email', $email);
            if ($user) {
                $error['email'] = "E-mail exists.";
            }
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['id'] = $id;
            $GLOBALS['email'] = $email;
            
            $mvc->render(dirname(__FILE__)."/views/_register_.php");
            return;
        }
        
        $nickname = $nickname ? $nickname : $id;
        
        $serial = user_create(array('id'=>$id, 'email'=>$email, 'password'=>$password));
        
        if ($serial) {
            $mvc->setMessage("message", "Regiter success.");
            $mvc->redirect(REQUEST_BASE);
        }
    }
}

/**
 * com_yizin_site_login
 *
 * 用户登陆
 *
 * @param object $matches
 * 	 $matches[1]
 *
 * @mvc
 * 	 跳转：$mvc->redirect($url);
 */
 
function com_yizin_site_login($matches) {
    global $mvc;
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $GLOBALS['message'] = $mvc->getMessage('message');
        $GLOBALS['redirect'] = $matches[1];
        $mvc->render(dirname(__FILE__)."/views/_login_.php");
    } elseif ($method == "POST") {
        global $mvc;
        $id = trim($_POST['id']);
        $password = trim($_POST['password']);
        $error = array();
        if ($id == "") {
            $error['id'] = "Username is required.";
        } elseif ($password == "") {
            $error['password'] = "Password is required.";
        }
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['redirect'] = $_POST['redirect'];
            $mvc->render(dirname(__FILE__)."/views/_.php");
            return;
        }
        if (!Utils::isEmail($id)) {
            $user = user_getByField("id", $id);
        } else {
            $user = user_getByField("email", $id);
        }
        if (!$user || !user_auth($user['serial'], $password)) {
            $mvc->setMessage("message", "Login Failed. Please check your username and password again.");
            $mvc->redirect(REQUEST_BASE."login/".$_POST['redirect']);
            return;
        }
        
        $user['before_last_access_time'] = $user['last_access_time'];
        $user['last_access_time'] = date('Y-m-d H:i:s', time());
        user_update($user);
        
        session_setCurrentUser($user['serial']);
        
        $url = $_POST['redirect'] == '' ? REQUEST_BASE : REQUEST_BASE.$_POST['redirect'];
        $mvc->setMessage("message", "Login successfully.");
        $mvc->redirect($url);
    }
}

/**
 * com_yizin_site_logout
 *
 * 退出登录
 *
 * @mvc
 * 	 跳转至：$mvc->redirect(REQUEST_BASE);
 */
 
function com_yizin_site_logout($matches) {

    global $mvc;
    
    session_unsetCurrentUser();
    $mvc->setMessage("message", "Logout successfully.");
    $mvc->redirect(REQUEST_BASE);
}

/**
 * com_yizin_site_account_profile
 *
 * 修改用户基本资料
 * @mvc
 * 	 get：渲染：$mvc->render(dirname(__FILE__)."/views/_account_profile_.php");
 * 	 post：if（表单有错误）渲染：$mvc->render(dirname(__FILE__)."/views/_account_profile_.php");
 *         else：跳转：$mvc->redirect(REQUEST_BASE."account/profile/");
 */
 
function com_yizin_site_account_profile($matches) {

    global $mvc;
    global $currentUser;
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $GLOBALS['email'] = $currentUser['email'];
        $GLOBALS['nickname'] = $currentUser['nickname'];
        $user = user_getXByField("serial", $currentUser['serial']);
        $GLOBALS['description'] = $user['description'];
        if ($user['image']) {
            $userPath = Utils::getPathBySerial($user['serial'], true);
            $resourcePath = RESOURCE_BASE.'com.yizin.site/'.$userPath;
            $GLOBALS['image'] = $resourcePath.$user['image'];
        }
        $GLOBALS['message'] = $mvc->getMessage('message');
        $mvc->render(dirname(__FILE__)."/views/_account_profile_.php");
    } elseif ($method == "POST") {
        $email = trim($_POST['email']);
        $nickname = trim($_POST['nickname']);
        $description = trim($_POST['description']);
        $image = $_FILES['image'];
        
        $error = array();
        
        if ($email == "") {
            $error['email'] = "E-mail is required.";
        }
        if (!Utils::isEmail($email)) {
            $error['email'] = "Invalid E-mail address.";
        }
        if ($nickname != "") {
            if (strlen($nickname) < 4)$error['nickname'] = "Nick name is too short.";
            if (strlen($nickname) > 20)$error['nickname'] = "Nick name is too long.";
        }
        
        $user = user_getByField('email', $email);
        if ($user && $user['serial'] != $currentUser['serial']) {
            $error['email'] = "E-mail address exists.";
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['email'] = $email;
            $GLOBALS['nickname'] = $nickname;
            $GLOBALS['description'] = $description;
            
            $mvc->render(dirname(__FILE__)."/views/_account_profile_.php");
            return;
        }
        
        $resourceBase = RESOURCE_PATH.DIRECTORY_SEPARATOR.'com.yizin.site';
        $time = time();
        if (isset($image) && $image['size'] != 0) {
            if (is_dir($resourceBase)) {
                $userPath = Utils::getPathBySerial($currentUser['serial']);
                $path = $resourceBase.DIRECTORY_SEPARATOR.$userPath;
                try {
                    if (!file_exists($path)) {
                        Utils::recur_mkdirs($path);
                    }
                    $imageResizer = new SimpleImage();
                    $imageResizer->load($image['tmp_name']);
                    $imageResizer->resizeToWidth(50);
                    $imageResizer->save($path.DIRECTORY_SEPARATOR.intval($time, 16).'.'.Utils::fileext($image['name']));
                    $currentUser['image'] = intval($time, 16).'.'.Utils::fileext($image['name']);
                }
                catch(exception $e) {
                    echo $e->getmessage();
                }
            }
        }
        
        $currentUser['email'] = $email;
        $currentUser['nickname'] = $nickname ? $nickname : $user['id'];
        $currentUser['description'] = $description;
        
        user_update($currentUser);
        $mvc->setMessage("message", "Profile updated.");
        $mvc->redirect(REQUEST_BASE."account/profile/");
        
    }
}

/**
 * com_yizin_site_account_password
 *
 * 用户修改密码
 * @mvc
 * 	　get：渲染：$mvc->render(dirname(__FILE__)."/views/_account_password_.php");
 * 	　post:if（表单有错误）渲染：$mvc->render(dirname(__FILE__)."/views/_account_password_.php");
 *         else：跳转：$mvc->redirect(REQUEST_BASE."account/password/");
 */
 
function com_yizin_site_account_password($matches) {

    global $mvc;
    global $currentUser;
    
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "GET") {
        $GLOBALS['message'] = $mvc->getMessage('message');
        $mvc->render(dirname(__FILE__)."/views/_account_password_.php");
    } elseif ($method == "POST") {
        $oldPassword = trim($_POST['oldPassword']);
        $password = trim($_POST['password']);
        $password1 = trim($_POST['password1']);
        
        $error = array();
        if ($oldPassword == "") {
            $error['oldPassword'] = "Old password is required.";
        } elseif ($password == "") {
            $error['password'] = "New password is required.";
        } elseif (strlen($password) < 6 || strlen($password) > 30) {
            $error['password'] = "Password size must between 6 and 30.";
        } elseif ($password1 != $password) {
            $error['password1'] = "The two new password is different. Please check it again.";
        }
        
        if (count($error) == 0) {
            if (!user_auth($currentUser['serial'], $oldPassword)) {
                $error['oldPassword'] = "Old password is wrong.";
            }
        }
        
        if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $mvc->render(dirname(__FILE__)."/views/_account_password_.php");
            return;
        }
        
        $currentUser['password'] = $password;
        
        user_update($currentUser);
        $mvc->setMessage("message", "Password changed.");
        $mvc->redirect(REQUEST_BASE."account/password/");
        
    }
}
function com_yizin_site_forget($matches) {
	global $mvc,$featureManager;
    $GLOBALS['message'] = $mvc->getMessage('message');
    $mvc->render(dirname(__FILE__)."/views/_forget_.php");
}


function site_index($matches) {
    global $mvc;
	global $future_session_list;
	global $current_session_list;
	global $past_session_list;
	
	$current_session_list = service_site_get_index_session_list('current');
	$count = count($current_session_list);
	if ($count < 4) {
		$future_session_list = service_site_get_index_session_list('future', 4 - $count);
		$count += count($future_session_list);
		if ($count < 4) {
			$past_session_list = service_site_get_index_session_list('past', 4-$count);
		}
	}
	
    $mvc->render(dirname(__FILE__)."/views/_.php");
}

function com_yizin_site_admin_login_($matches) {

    global $mvc,$featureManager;
    $mvc->render(dirname(__FILE__)."/views/_admin_index_.php");
}

function com_yizin_site_member_show($matches) {

    global $mvc,$member,$featureManager;
    $serial = $matches[1];
    
    $member = user_getXByField('serial', $serial);
    
    $reply['type'] = "member";
    $reply['domain_serial'] = $serial;
    $featureManager->apply("com.yizin.platform.reply", $reply);
    $GLOBALS['reply'] = $reply['html'];
    
    $context['serial'] = $member['serial'];
    $context['limit'] = 3;
    $featureManager->apply("com.yizin.review.get.by.user", $context);
    $GLOBALS['reviews'] = $context['html'];
    $mvc->render(dirname(__FILE__)."/views/_member_show_.php");
}

function site_about () {
	global $mvc;

    $mvc->render(dirname(__FILE__)."/views/_about_.php");
}

function site_contact () {
	global $mvc;

    $mvc->render(dirname(__FILE__)."/views/_contact_.php");
}

global $mvc;
$mvc = new MVC(Array(
	 '{^/$}'=>'site_index',
	 '{^/home/$}'=>'site_index',
	 '{^/about/$}'=>'site_index',
	 '{^/contact/$}'=>'site_index',
     '{^/login/(.+)?$}'=>'com_yizin_site_login',
     '{^/logout/$}'=>'com_yizin_site_logout',
     '{^/account/profile/$}'=>'com_yizin_site_account_profile',
     '{^/account/password/$}'=>'com_yizin_site_account_password',
     '{^/register/$}'=>'com_yizin_site_register',
     '{^/forget/$}'=>'com_yizin_site_forget',
     '{^/admin/$}'=>'com_yizin_site_admin_login_',
     '{^/admin/user/user/(page/([^/]+)/)?$}'=>'com_yizin_site_admin_user_user_page_2',
     '{^/admin/user/user/(all|id|email|nickname|role|city|company)/([^/]*)/(page/([^/]+)/)?}'=>'com_yizin_site_admin_user_user_1_2_page_4',
     '{^/admin/user/user/new/$}'=>'com_yizin_site_admin_user_user_new',
     '{^/admin/user/user/create/$}'=>'com_yizin_site_admin_user_user_create',
     '{^/admin/user/user/delete/$}'=>'com_yizin_site_admin_user_user_delete',
     '{^/admin/user/user/([^/]+)/$}'=>'com_yizin_site_admin_user_user_1',
     '{^/admin/user/profile/([^/]+)/$}'=>'com_yizin_site_admin_user_profile_1',
     '{^/admin/user/role/(page/([^/]+)/)?$}'=>'com_yizin_site_admin_user_role_page_2',
     '{^/admin/user/role/new/$}'=>'com_yizin_site_admin_user_role_new',
     '{^/admin/user/role/create/$}'=>'com_yizin_site_admin_user_role_create',
     '{^/admin/user/role/delete/$}'=>'com_yizin_site_admin_user_role_delete',
     '{^/admin/user/role/grant/.*$}'=>'com_yizin_site_admin_user_role_grant',
     '{^/admin/user/role/([^/]+)/$}'=>'com_yizin_site_admin_user_role_1',
     '{^/admin/user/role/([^/]+)/privilege/$}'=>'com_yizin_site_admin_user_role_1_privilege',
     ));
$mvc->dispatch($GLOBALS['uri']);

?>
